package com.treasure.hunt.mine

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.fragment.app.FragmentTransaction
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import com.blankj.utilcode.util.*
import com.google.android.material.tabs.TabLayout
import com.module.lemlin.base.*
import com.module.lemlin.mode.ViewModeFragment
import com.module.lemlin.rxhttp.Status
import com.module.lemlin.rxhttp.msg
import com.module.lemlin.util.qqShareImage
import com.module.lemlin.util.wxShareImage
import com.treasure.hunt.R
import com.treasure.hunt.app.AppConstance
import com.treasure.hunt.entity.CardList
import com.treasure.hunt.getDiskCacheDirectoryImage
import com.treasure.hunt.mode.CardViewMode
import com.treasure.hunt.popup.DialogFlopPopup
import com.treasure.hunt.popup.DialogSharePopup
import com.youth.banner.adapter.BannerAdapter
import com.youth.banner.listener.OnPageChangeListener
import kotlinx.android.synthetic.main.fragment_card_reveal.*
import rxhttp.RxHttp

class CardRevealFragment : ViewModeFragment<CardViewMode>() {

    companion object {
        fun newInstance(): CardRevealFragment {
            return CardRevealFragment()
        }
    }

    private var cardList: CardList? = null

    private val flopPopup: DialogFlopPopup by lazy {
        DialogFlopPopup(context = requireContext(), onAnimationEnd = {})
    }

    private var shareType: Int = 1

    private var shareAction: Int = 1

    private val sharePopup: DialogSharePopup by lazy {
        DialogSharePopup(context = requireContext()) { view ->
            when (view.id) {
                R.id.tvDialogShareWX -> shareType = 1
                R.id.tvDialogShareQQ -> shareType = 2
            }
            cardList?.let {
                viewModel.otherShareImage(shareAction, it.id)
            }
        }
    }

    override val layoutResId: Int
        get() = R.layout.fragment_card_reveal

    override fun viewModel(): CardViewMode {
        return createViewModel(requireActivity())
    }

    override fun initView() {

        val height: Int =
            ((ScreenUtils.getAppScreenHeight() - ConvertUtils.dp2px(45f) - BarUtils.getStatusBarHeight()) / 5.8 * 3.8).toInt()

        bvMineBanner.layoutParams.apply {
            if (height > ConvertUtils.dp2px(380f)) {
                this.height = ConvertUtils.dp2px(380f)
            }
        }

        bvMineBanner.addOnPageChangeListener(object : OnPageChangeListener {
            override fun onPageScrollStateChanged(state: Int) = Unit

            override fun onPageScrolled(
                position: Int, positionOffset: Float, positionOffsetPixels: Int
            ) = Unit

            override fun onPageSelected(position: Int) {
                tlMineCardKindBody.getTabAt(position)?.select()
                viewModel.cardListLiveData.value?.httpData?.data?.let {
                    if (it[position].type == 2) {
                        llMineCardAction.visibility = View.GONE
                        tvMineGoChange.visibility = View.VISIBLE
                    } else {
                        tvMineGoChange.visibility = View.GONE
                        llMineCardAction.visibility = View.VISIBLE
                    }
                    cardList = it[position]
                }
            }
        })

        tlMineCardKindBody.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabReselected(tab: TabLayout.Tab?) = Unit

            override fun onTabUnselected(tab: TabLayout.Tab?) = Unit

            override fun onTabSelected(tab: TabLayout.Tab?) {
                bvMineBanner.currentItem = tab?.position ?: 0
            }
        })

        tvMineGoChange.setOnClickListener {

            viewModel.cardListLiveData.value?.httpData?.data?.let {
                if (it[bvMineBanner.currentItem].type != 2) {
                    return@setOnClickListener
                }
                val transaction: FragmentTransaction =
                    requireActivity().supportFragmentManager.beginTransaction()
                transaction.setCustomAnimations(
                    R.animator.slide_right_in, R.animator.slide_left_out,
                    R.animator.slide_left_in, R.animator.slide_right_out
                )
                transaction.replace(
                    R.id.flMineCardBody,
                    CardChangeFragment.newInstance(it[bvMineBanner.currentItem])
                )
                transaction.addToBackStack(null)
                transaction.commit()
            }
        }

        tvMineGoHunt.setOnClickListener {
            val maps: MutableMap<String, Any?> = mutableMapOf(
                "advertisement_type" to 5,
                "luck_draw_type" to 1
            )
            viewModel.videoType(maps)
        }

        tvMineGoGive.setOnClickListener {
            shareAction = 1
            sharePopup.showPopupWindow()
        }
    }

    override fun initViewMode() {
        viewModel.cardListLiveData.observe(this, Observer { response ->
            if (response.status == Status.FAILURE) {
                toast(response.throwable?.msg ?: "未知错误")
            }
            if (response.status != Status.SUCCESS)
                return@Observer
            response.httpData?.data?.let {
                if (it.size == 0)
                    return@Observer
                fillData(it)
            }
        })

        viewModel.videoTypeLiveData.observe(this, Observer { response ->
            if (response == null)
                return@Observer
            if (response.status == Status.FAILURE) {
                toast(response.throwable?.msg ?: "未知错误")
                viewModel.videoTypeLiveData.postValue(null)
            }
            if (response.status != Status.SUCCESS)
                return@Observer
            val cid: Int? = response.httpData?.data?.cid
                ?: return@Observer
            val codeId: String? = response.httpData?.data?.advertising_space
            if (codeId == null) {
                toast("广告位ID为空")
            } else if (cid == 1 && !codeId.isNullOrEmpty()) {
                viewModel.loadRewardVideoAdCSJ(mActivity = requireActivity(), codeId = codeId)
            } else if (cid == 2 && !codeId.isNullOrEmpty()) {
                viewModel.loadRewardVideoAdYLH(mActivity = requireActivity(), codeId = codeId)
            }
            viewModel.videoTypeLiveData.postValue(null)
        })

        viewModel.videoEndLiveData.observe(this, Observer { response ->
            if (response == null)
                return@Observer
            if (response.status == Status.FAILURE) {
                toast(response.throwable?.msg ?: "未知错误")
                viewModel.videoEndLiveData.postValue(null)
            }
            if (response.status != Status.SUCCESS)
                return@Observer
            response.httpData?.let {
                flopPopup.fillData(it.data).showPopupWindow()
                viewModel.videoNoReward(advertisementType = 3)
                viewModel.cardList()
            }
            viewModel.videoEndLiveData.postValue(null)
        })

        viewModel.videoNoRewardLiveData.observe(this as LifecycleOwner, Observer { response ->
            if (response == null)
                return@Observer
            if (response.status == Status.FAILURE) {
                viewModel.videoNoRewardLiveData.postValue(null)
            }
            if (response.status != Status.SUCCESS)
                return@Observer
            val cid: Int? = response.httpData?.data?.cid
            val codeId: String? = response.httpData?.data?.advertising_space
            if (cid == null) {

            } else if (cid == 1 && !codeId.isNullOrEmpty()) {
                viewModel.loadNativeExpressAdCSJ(mActivity = requireActivity(),codeId = codeId)
            } else if (cid == 2 && !codeId.isNullOrEmpty()) {
                viewModel.loadNativeExpressAdYLH(mActivity = requireActivity(),codeId = codeId)
            }
            viewModel.videoNoRewardLiveData.postValue(null)
        })

        viewModel.rewardVerifyAdLiveData.observe(
            this as LifecycleOwner,
            Observer { isRewardVerify ->
                if (!isRewardVerify)
                    return@Observer
                viewModel.videoTypeLiveData.value?.httpData?.data?.let {
                    viewModel.videoEnd(it.video_log_id)
                }
            })

        viewModel.viewAdLiveData.observe(this, Observer { view ->
            view?.let {
                flopPopup.fillViewAd(view)
            }
        })


        viewModel.otherUrlLiveData.observe(this, Observer { response ->
            if (response.status == Status.FAILURE)
                toast(response.throwable?.msg ?: "未知错误")
            if (response.status != Status.SUCCESS)
                return@Observer
            response.httpData?.data?.let { image ->
                if (image.url.isNullOrEmpty()) {
                    toast("分享图片地址为空")
                } else {
                    val isHttps: Boolean = image.url.substring(0, 5).contains("http") ||
                            image.url.substring(0, 5).contains("https")
                    RxHttp.get("${if (isHttps) "" else AppConstance.URL_IMAGE}${image.url}")
                        .asDownload("${getDiskCacheDirectoryImage(requireContext()).path}/share.png")
                        .subscribe({
                            requireActivity().runOnUiThread {
                                if (shareType == 1) {
                                    wxShareImage(it)
                                }
                                if (shareType == 2) {
                                    qqShareImage(requireActivity(), it)
                                }
                            }
                        }, {
                            toast(it.msg)
                        })
                }
            }
        })
    }

    private fun fillData(cardList: MutableList<CardList>) {
        llMineCardActionGroup.visibility = View.VISIBLE
        this.cardList = cardList[0]
        this.cardList?.let {
            if (it.type == 2) {
                llMineCardAction.visibility = View.GONE
                tvMineGoChange.visibility = View.VISIBLE
            } else {
                tvMineGoChange.visibility = View.GONE
                llMineCardAction.visibility = View.VISIBLE
            }
        }
        bvMineBanner.addBannerLifecycleObserver(this)
            .setBannerGalleryEffect(38, 18)
            .isAutoLoop(false)
            .setAdapter(object : BannerAdapter<CardList, RecyclerViewHolder>(cardList) {
                override fun onCreateHolder(parent: ViewGroup, viewType: Int): RecyclerViewHolder {
                    val view: View = LayoutInflater.from(parent.context)
                        .inflate(R.layout.item_banner_card, parent, false)
                    return RecyclerViewHolder(view)
                }

                override fun onBindView(
                    holder: RecyclerViewHolder,
                    data: CardList,
                    position: Int,
                    size: Int
                ) {
                    holder.itemView.findViewById<ImageView>(R.id.ivBannerCardImage).apply {
                        val isHttps: Boolean = data.image.substring(0, 5).contains("http") ||
                                data.image.substring(0, 5).contains("https")
                        loadCenterImage("${if (isHttps) "" else AppConstance.URL_IMAGE}${data.image}")
                        setOnClickListener {
                            shareAction = 4
                            sharePopup.showPopupWindow()
                        }
                    }
                    holder.itemView.findViewById<TextView>(R.id.tvBannerCardSend)
                        .setOnClickListener {
                            shareAction = 4
                            sharePopup.showPopupWindow()
                        }
                }
            }, (false))

        tlMineCardKindBody.apply {
            removeAllTabs()
            for ((index: Int, item: CardList) in cardList.withIndex()) {
                addTab(newTab().apply {
                    val view: View = LayoutInflater.from(requireContext())
                        .inflate(R.layout.item_card_kind, null)
                    val isHttps: Boolean = item.image.substring(0, 5).contains("http") ||
                            item.image.substring(0, 5).contains("https")
                    view.findViewById<ImageView>(R.id.ivCardKindIcon)
                        .loadRoundImage(
                            "${if (isHttps) "" else AppConstance.URL_IMAGE}${item.image}",
                            radius = 10
                        )
                    view.findViewById<TextView>(R.id.tvCardKindTitle).text = item.title
                    view.findViewById<TextView>(R.id.tvCardKindNum).text = item.num.toString()
                    customView = view
                    tag = index
                })
            }
        }
    }
}